#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
using std::cout;
using std::endl;
using std::cerr;
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::sort;


struct Record
{
    Record(const string &word,int frequency)
        :_word(word)
         ,_frequency(frequency) 
    {}
    string _word;
    int _frequency;
};

class Dictionary{
public:

    void read(const string &read_filename);
    void store(const string &store_filename);

private:
    vector<Record> _dict;
};
void Dictionary::read(const string &filename){
    ifstream ifs(filename);
    //判断文件是否打开成功
    if(!ifs.good()){
        cerr<<filename<<" is not found"<<endl;
        return;
    }

    _dict.reserve(2000);
    string word;
    while(ifs>>word){
        //判断单词是否是新的
        bool is_new = true;
        for(auto &it: _dict){
            if(it._word == word){
                it._frequency ++;
                is_new = false;
                break;
            }
        }
        if(is_new){
            _dict.emplace_back(word,1);
        }
    }
}

void Dictionary::store(const string &filename){
    //实现降序排列
    sort(_dict.begin(), _dict.end(),
         [](const Record &a, const Record &b) {
         return a._frequency > b._frequency;
         });
    ofstream ofs(filename);

    //遍历容器
    for(auto &it:_dict){
        ofs<<it._word<<" "<<it._frequency<<endl;
    }
}

int main()
{
    Dictionary d1;
    d1.read("/root/3th/alxy/The_Holy_Bible.txt");
    //d1.read("/root/3th/alxy/test1.txt");
    d1.store("dict.txt");

    return 0;
}

